<template>
    <div class="share">
        <view class="shade" v-show="showShade">
            <view class="shade-bg"></view>
            <view class="shade-btn" @tap.stop='saveImage'>保存图片</view>
        </view>

        <view class="canvas-box" v-show="showShade">
            <canvas canvas-id="shareCanvas" v-bind:style="{ width: '100%', height: drawHeight + 'px' }"></canvas>
        </view>
        <button type='primary' class='openSetting' open-type="openSetting"
@opensetting='handleSetting' v-show='openSettingBtnHidden'>去授权开启保存图片功能吧！</button>
    </div>
</template>
<script>
import { mapState } from "vuex";
export default {
  data() {
    return {
      portrait_temp: "",
      qrcode_temp: "",
      image_temp: "",
      drawWidth: 0,
      drawHeight: 0,
      scale: 1,
      windowWidth: 0,
      openSettingBtnHidden: false
    };
  },
  async created() {
    let res = wx.getSystemInfoSync();
    this.windowWidth = res.windowWidth;
    this.drawWidth = res.windowWidth * 0.7;
    this.drawHeight = res.windowHeight * 0.56;
  },
  computed: {
    ...mapState(["showShade"])
  },
  onHide() {
    this.openSettingBtnHidden = false;
  },
  methods: {
    //分享到微信朋友圈
    shareToMoments(title, image) {
      this.$store.state.showShade = true;
      wx.showLoading();
      let that = this;
      //缓存canvas绘制小程序二维码
      wx.downloadFile({
        url: "https://dr.xinwangd.com/public/static/code.png",
        success: function(res) {
          //缓存二维码
          that.qrcode_temp = res.tempFilePath;
          wx.downloadFile({
            url: image + "",
            success: function(res) {
              //缓存图片
              that.image_temp = res.tempFilePath;
              //开始绘制图片
              that.drawImage(title, image);
            }
          });
        }
      });
    },
    drawImage(title, image) {
      this.openSettingBtnHidden = false;
      //绘制canvas图片
      let that = this;
      const ctx = wx.createCanvasContext("shareCanvas");
      let portraitPath = that.portrait_temp;
      let qrPath = that.qrcode_temp;
      let imagePath = that.image_temp;
      let drawWidth = that.drawWidth;
      let drawHeight = that.drawHeight;
      that.scale = 1.6;
    
      //绘制背景
      ctx.setFillStyle("#fff");
      ctx.fillRect(0, 0, drawWidth, drawHeight);
      // 绘制二维码
      ctx.drawImage(
        qrPath,
        0,
        0.73 * drawHeight,
        0.3 * drawWidth,
        0.3 * drawWidth
      );

      //   //绘制文字
      var chr = title.split(""); //这个方法是将一个字符串分割成字符串数组
      var temp = "";
      var row = [];
      ctx.setFontSize(16);
      ctx.setFillStyle("#000");
      for (var a = 0; a < chr.length; a++) {
        if (ctx.measureText(temp).width < 0.6 * drawWidth) {
          temp += chr[a];
        } else {
          a--; //这里添加了a-- 是为了防止字符丢失，效果图中有对比
          row.push(temp);
          temp = "";
        }
      }
      row.push(temp);
      //如果数组长度大于2 则截取前两个
      if (row.length > 2) {
        var rowCut = row.slice(0, 2);
        var rowPart = rowCut[1];
        var test = "";
        var empty = [];
        for (var a = 0; a < rowPart.length; a++) {
          if (ctx.measureText(test).width < 0.6 * drawWidth) {
            test += rowPart[a];
          } else {
            break;
          }
        }
        empty.push(test);
        var group = empty[0] + "..."; //这里只显示两行，超出的用...表示
        rowCut.splice(1, 1, group);
        row = rowCut;
      }
      for (var b = 0; b < row.length; b++) {
        ctx.fillText(row[b], 0.3 * drawWidth, 0.8 * drawHeight + b * 20);
      }
      ctx.setFontSize(14);
      ctx.setFillStyle("#d43d3d");
      ctx.fillText(
        "长按识别二维码查看全文",
        0.3 * drawWidth,
        0.92 * drawHeight
      );
      //绘制图片
      ctx.drawImage(imagePath, 0, 0, drawWidth, 0.7 * drawHeight);
      ctx.draw();
      wx.hideLoading();
    },
    savaImageToPhoto() {
      // this.openSettingBtnHidden = true;
      let that = this;
      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        width: that.windowWidth,
        height: that.windowWidth * that.scale,
        canvasId: "shareCanvas",
        success: function(res) {
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success(result) {
              wx.showModal({
                title: "成功保存图片",
                content: "已成功为您保存图片到手机相册，请自行前往朋友圈分享",
                showCancel: false,
                confirmText: "知道了"
              });
            }
          });
        }
      });
    },
    //将绘制的图片设置大小后保存图片到本地
    saveImage() {
      var that = this;
      //获取相册授权
      wx.getSetting({
        success(res) {
          if (!res.authSetting["scope.writePhotosAlbum"]) {
            wx.authorize({
              scope: "scope.writePhotosAlbum",
              success() {
                //这里是用户同意授权后的回调
                that.savaImageToPhoto();
                that.openSettingBtnHidden = false;
              },
              fail() {
                //这里是用户拒绝授权后的回调
                that.openSettingBtnHidden = true;
              }
            });
          } else {
            //用户已经授权过了
            that.savaImageToPhoto();
          }
        }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.openSetting {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 100rpx;
}
.canvas-box {
  width: 70%;
  height: 56%;
  position: fixed;
  text-align: center;
  left: 0;
  right: 0;
  margin: 0 auto;
  top: 15%;
  z-index: 100;
}

.shade {
  width: 70%;
  height: 70%;
  position: fixed;
  margin: auto;
  text-align: center;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  z-index: 99;
}

.shade .shade-bg {
  width: 100%;
  height: 80%;
  background: #fff;
}

.shade .shade-btn {
  margin-top: 30rpx;
  display: inline-block;
  background: #d43d3d;
  padding: 8rpx 30rpx;
  font-size: 36rpx;
  border-radius: 30rpx;
  color: #fff;
}
</style>


